package com.scholarship.modules.student.controller;

import com.scholarship.common.entity.RetCode;
import com.scholarship.common.entity.RetResponse;
import com.scholarship.common.entity.RetResult;
import com.scholarship.common.utils.FileUtil;
import com.scholarship.common.utils.UploadToYun;
import com.scholarship.modules.student.service.StuApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.Calendar;

/**
 * @author: huanghao
 * @date: 2021/3/9 16:10
 * @description: 文件控制层
 * @modifiedBy:
 */
@Api(tags = {"文件控制层"})
@RestController
public class FileController {
    //日志logger
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private StuApplicationService stuApplicationService;

    @Autowired
    UploadToYun uploadToYun;
    /*
    * 由于上传文件必须使用MultipartFile对象
    * 但是该对象又不能和其他参数混用
    * 所以为了针对同时传输数据+文件的场景
    * 解决思路是先让前端单独调用文件上传接口
    * 将文件先上传至服务器保存，保存成功则后台返回文件存储的url给前端（以String的形式）
    * 然后前端接受到该url后，将url和其他普通数据再次调用接口一起返回给后台
    */

    /**
     * 上传单个文件不进行保存
     *
     * @author zjh
     * @date 2021/8/22
     * @param multipartFile
     * @return
     */
    @ApiOperation("上传单个文件 @Z.J.H")
    @PostMapping("/file/upload")
    public RetResult uploadFile(@RequestParam("file") MultipartFile multipartFile){
        try{
            String fileUrl = "https://cdn.zhz1314.cn"+uploadToYun.saveFile(multipartFile);
            if (fileUrl == null) {
                return RetResponse.makeRsp(RetCode.FAIL, "原位置已存在文件");
            }
            return RetResponse.makeRsp(RetCode.SUCCESS, "上传文件成功", fileUrl);
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return RetResponse.makeRsp(RetCode.FAIL, "上传文件失败");
        }
    }

    /*
        文件上传接口
        user_id : String        用户id
        tableId : Integer       表Id
        file : MultipartFile    文件
     */
    @ApiOperation("上传单个文件")
    @PostMapping("/file/uploadFile")
    public RetResult uploadFile(@RequestParam("userId") String user_id, @RequestParam("tableId") Integer tableId, @RequestParam("file") MultipartFile multipartFile){
        String fileUrl = null;
        try{
            fileUrl = "https://cdn.zhz1314.cn"+uploadToYun.saveFile(multipartFile);
            String import_year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            stuApplicationService.insertFile(user_id,fileUrl,tableId,import_year);
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return RetResponse.makeRsp(RetCode.FAIL, "上传文件失败");
        }
        if (fileUrl == null)
            return RetResponse.makeRsp(RetCode.FAIL, "原位置已存在文件");
        return RetResponse.makeRsp(RetCode.SUCCESS, "上传文件成功", fileUrl);
    }
//    public RetResult uploadFile(@RequestParam("userId") String user_id, @RequestParam("fileType") String fileType, @RequestParam("file") MultipartFile multipartFile)
//    {
//        String fileUrl = null;
//        String filePath = "G:\\BNUZ\\" + user_id + "\\";
//        try{
//            fileUrl = FileUtil.uploadFile(multipartFile.getBytes(), filePath, multipartFile.getOriginalFilename());
//        }
//        catch (IOException e) {
//            e.printStackTrace();
//            return RetResponse.makeRsp(RetCode.FAIL, "上传文件失败");
//        }
//        if (fileUrl == null)
//            return RetResponse.makeRsp(RetCode.FAIL, "上传文件失败");
//        return RetResponse.makeRsp(RetCode.SUCCESS, "上传文件成功", fileUrl);
//    }

    /*
    * 多文件上传接口
    */
    @ApiOperation("上传多个文件")
    @PostMapping("/file/uploadFiles")
    public RetResult uploadFiles(@RequestParam("fileList") MultipartFile[] multipartFileList)
    {
        String filePath = "G:\\BNUZ\\";
        String[] fileUrlList = new String[multipartFileList.length];
        try {
            int cnt = 0;
            for (MultipartFile file : multipartFileList) {
                String fileUrl = FileUtil.uploadFile(file.getBytes(), filePath, file.getOriginalFilename());
                fileUrlList[cnt++] = fileUrl;
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage());
            return RetResponse.makeRsp(RetCode.FAIL, "上传文件失败");
        }

        return RetResponse.makeRsp(RetCode.SUCCESS, "上传成功", fileUrlList);
    }


}
